<template>
	<view class="wapper">
		<button type="primary" class="choose-btn" @click="chooseImage">选择识别图片</button>
		<image id="sourceImg" class="preview-img" v-if="previewImageSrc" mode="aspectFit" :src="previewImageSrc"></image>
		<image id="hideImg" style="display: none;"></image>
		<uni-list v-for="result in results">
			<uni-list-item  :class="{ color: result.color}" :title="result.label" :note="result.intro" :thumb="result.src"
			 thumb-size="lg" >
			 </uni-list-item>
			 <progress :percent="result.score" show-info stroke-width="3" />		 
		</uni-list>
	</view>
</template>

<script>
	import * as tf from '@tensorflow/tfjs'
	import intro from '../../static/intro.js'
	export default {
		data() {
			return {
				model: {},
				previewImageSrc : '',
				results : []
			}
		},
		async onLoad() {
			const DATA_URL = 'https://7463-tcb-csq0wy5b65eabf-0d365c00ed906-1306152027.tcb.qcloud.la'
			this.model = await  tf.loadLayersModel(DATA_URL + '/model.json')
			this.classes = await uni.request(DATA_URL + '/classes.json').then(res => res.json())
		},
		methods: {
			chooseImage(){
				uni.chooseImage({
				    count: 1, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album'], //从相册选择
				    success: async (res) => {
						this.previewImageSrc = res.tempFilePaths[0];
						const tempFile = res.tempFiles[0];
						console.log(tempFile)
						console.log(tempFile.path)
						// const this = this;
						const pred = tf.tidy(() => {
							const x = this.imgPath2x(tempFile)
							return this.model.predict(x)
						})
						pred.print()
						this.results = pred.arraySync()[0]
						.map((score,i) => ({ score: Math.round(score * 10000,2)/100, label :this.classes[i], ...intro[this.classes[i]]}))
						.sort((a,b) => b.score-a.score)
	
						// this.result = results && {..., ...intro[results[0].label]}
						console.log(this.results)
				    }
				});
				
			},
			async imgPath2x(imgPath){
				 // tf.tidy 及时清理转换后的内存
				 const buffer = await readFilePath(imgPath);
				return tf.tidy(() => {
					const imgTs = tf.node.decodeImage(new Uint8Array(buffer))
					const imgTsResized = tf.image.resizeBilinear(imgTs, [224,224])
					return imgTsResized.toFloat().sub(255/2).div(255/2).reshape([1,224,224,3])				
				})
					
				
			},
			readFilePath(imgPath){
				new Promise(resolve => {
					plus.io.resolveLocalFileSystemURL(imgPath,function(entry) {
						//读取文件  
						entry.file(function(file) {
							console.log(file)
							var reader = new plus.io.FileReader();
							const result = reader.readAsDataURL(file); // 以URL格式读取文件
							reader.onload = () =>{ 
								let base64 = result.split(',')[1]; // 获取base64字符串
								const buffer = uni.base64ToArrayBuffer(base64); // 转换为arrayBuffer格式
								resolve(buffer)
							}
						});
					});
				})
			}	
		}
	}
</script>

<style>
	.wapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.choose-btn {
		width: 100%;
	}
	.preview-img {
		margin-top: 10rpx;
	}
	.result {
		display: inline;
		/* flex-direction: row; */
		/* align-items: center; */
		/* justify-content: center; */
	}
	
</style>
